package com.JUC.cha03.sec06;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * future常用方法
 *
 * 4.对计算速度进行选用
 *  ---- resultA、resultB    是结果
 *  4.1. resultA.applyToEither(resultB, function -> {return 结果})
 */
public class CompletableFutureAPI4Demo {

    public static void main(String[] args) {

        CompletableFuture<String> resultA = CompletableFuture.supplyAsync(() -> {
            System.out.println(" come in A");
            // 暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "A is winner";
        });

        CompletableFuture<String> resultB = CompletableFuture.supplyAsync(() -> {
            System.out.println(" come in B");
            // 暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "B is winner";
        });


        CompletableFuture<String> result = resultA.applyToEither(resultB, f -> {
            return f;
        });

        System.out.println("winner ---- " + Thread.currentThread().getName() + "\t" + result.join());

    }


}
